import React, { useEffect, useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Input, Tag, message } from 'antd';
import { doFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';

const AddTag = ({ tags, refresh }) => {
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef(null);

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      refresh?.();
      setInputVisible(false);
      setInputValue('');
    },
  });

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  const showInput = () => {
    setInputVisible(true);
  };
  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    if (loading) {
      return;
    }
    if(!inputValue){
      setInputVisible(false);
    }

    if (inputValue && tags.indexOf(inputValue) === -1) {
      run?.({ url: '/wbn-api/tag/create_custom_tag', params: { name: inputValue } });
    }
    if (inputValue && tags.indexOf(inputValue) !== -1) {
      message.error('已存在同名标签，不可重复添加！');
    }
  };

  const tagPlusStyle = {
    borderStyle: 'dashed',
  };
  return (
    <>
      {inputVisible ? (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={{
            width: 78,
          }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      ) : (
        <Tag onClick={showInput} style={tagPlusStyle}>
          <PlusOutlined /> 添加
        </Tag>
      )}
    </>
  );
};
export default AddTag;
